package com.adam.example.aggregation.bucket;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.aggregations.Aggregate;
import co.elastic.clients.elasticsearch._types.aggregations.Buckets;
import co.elastic.clients.elasticsearch._types.aggregations.DateRangeAggregate;
import co.elastic.clients.elasticsearch._types.aggregations.RangeBucket;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import com.adam.example.ElasticsearchClientHolder;

import java.io.IOException;
import java.util.List;

public class DateRangeAggregationExample {

    public static void main(String[] args) throws IOException {
        ElasticsearchClient elasticsearchClient = ElasticsearchClientHolder.getINSTANCE().initializeAndGetClient();

        SearchResponse<Void> searchResponse = elasticsearchClient.search(builder -> builder
                        .index("test_books")
                        .size(0)
                        .aggregations("agg", aggregationBuilder -> aggregationBuilder
                                .dateRange(dateRangeAggregationBuilder -> dateRangeAggregationBuilder
                                        .field("publish_time")
                                        .format("yyyy-MM-dd")
                                        .ranges(dateRangeExpressionBuilder -> dateRangeExpressionBuilder
                                                .to(fieldDateMatchBuilder -> fieldDateMatchBuilder
                                                        .expr("now-24M/M")
                                                )
                                        )
                                        .ranges(dateRangeExpressionBuilder -> dateRangeExpressionBuilder
                                                .from(fieldDateMatchBuilder -> fieldDateMatchBuilder
                                                        .expr("now+24M/M")
                                                )
                                        )
                                )
                        )
                , Void.class);
        Aggregate aggregate = searchResponse.aggregations().get("agg");
        DateRangeAggregate dateRangeAggregate = aggregate.dateRange();
        Buckets<RangeBucket> buckets = dateRangeAggregate.buckets();
        List<RangeBucket> bucketList = buckets.array();
        for(RangeBucket rangeBucket: bucketList) {
            System.out.println(rangeBucket.key() + ":" + rangeBucket.docCount());
        }

        ElasticsearchClientHolder.getINSTANCE().close();
    }

}
